package com.txzt.gaea.provide.service.biz;

import com.alibaba.fastjson.JSONObject;
import com.txzt.gaea.common.core.base.context.AdminUserContext;
import com.txzt.gaea.provide.enums.FileTypeEnum;
import com.txzt.gaea.provide.model.FileInfo;
import com.txzt.gaea.provide.service.FileInfoService;
import com.txzt.gaea.vo.AdminUserVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Slf4j
@Service
public class FileInfoBizService {
    @Value("${file.upload-url}")
    String uploadUrl;

    @Value("${file.download-url}")
    String downloadUrl;

    @Autowired
    private FileInfoService fileInfoService;


    /**
     * 上传文件
     *
     * @param file 文件
     */
    public Map<String, Object> upload(MultipartFile file, String fileDesc, String toolCode) throws Exception {
        AdminUserVO adminUserVO = AdminUserContext.getUser();
        String fileExt = getFileExt(Objects.requireNonNull(file.getOriginalFilename()));
        //文件上传
        Map<String, Object> result = this.post2File(file, fileDesc, toolCode);
        FileInfo fileInfo = FileInfo.builder().
                fileName(file.getOriginalFilename()).
                fileUrl((String)result.get("fileUrl")).
//                fileUrl(downloadUrl + "/" + result.get("fileNameS")).
                fileType(FileTypeEnum.getByCode(fileExt).getValue()).
                fileDesc(fileDesc).
                fileSize(file.getSize()).
                fileExt(fileExt).
                createTime(new Date()).
                createBy(null != adminUserVO ? adminUserVO.getId() : 0).
                toolCode(toolCode).
                isDelete(0).build();
        fileInfoService.save(fileInfo);
        result.put("fileId", fileInfo.getId());
        result.put("fileUrl", fileInfo.getFileUrl());
        result.put("fileName", file.getOriginalFilename());
        result.put("fileDesc", fileDesc);
        result.put("fileExt", fileExt);
        return result;
    }

    /**
     * 上传文件
     *
     * @param file 文件
     */
    public Map<String, Object> uploadNew(MultipartFile file, String projectNo, Integer bizType, String fileDesc, String toolCode) throws Exception {
        AdminUserVO adminUserVO = AdminUserContext.getUser();
        String fileExt = getFileExt(Objects.requireNonNull(file.getOriginalFilename()));
        //文件上传
        Map<String, Object> result = this.post2File(file, fileDesc, toolCode);
        FileInfo fileInfo = FileInfo.builder().
                fileName(file.getOriginalFilename()).
                fileUrl((String)result.get("fileUrl")).
//                fileUrl(downloadUrl + "/" + result.get("fileNameS")).
        fileType(FileTypeEnum.getByCode(fileExt).getValue()).
                fileDesc(fileDesc).
                fileSize(file.getSize()).
                fileExt(fileExt).
                createTime(new Date()).
                createBy(null != adminUserVO ? adminUserVO.getId() : 0).
                toolCode(toolCode).
                projectNo(projectNo).
                bizType(bizType).
                isDelete(0).build();
        fileInfoService.save(fileInfo);
        result.put("fileId", fileInfo.getId());
        result.put("fileUrl", fileInfo.getFileUrl());
        result.put("fileName", file.getOriginalFilename());
        result.put("fileDesc", fileDesc);
        result.put("fileExt", fileExt);
        return result;
    }


    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 扩展名
     */
    private static String getFileExt(String fileName) {
        int begin = fileName.indexOf(".") + 1;
        int last = fileName.length();
        return fileName.substring(begin, last);
    }

    @SneakyThrows
    public Map<String,Object> post2File(MultipartFile file, String fileDesc, String toolCode){
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        };
        form.add("file", byteArrayResource);
        form.add("fileDesc", fileDesc);
        form.add("toolCode", toolCode);
        //用HttpEntity封装整个请求报文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        RestTemplate restTemplate = new RestTemplate();
        String flag = restTemplate.postForObject(uploadUrl, files, String.class);
        //json对象转Map
        Map<String, Object> map = JSONObject.parseObject(flag);
         return (Map<String, Object>) map.get("data");
    }

}
